<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i>
          食谱管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.category"
          placeholder="就餐类别"
          class="handle-select mr10"
        >
          <el-option key="4" label="全部类型" value=""></el-option>
          <el-option key="0" label="早餐" value="0"></el-option>
          <el-option key="1" label="午餐" value="1"></el-option>
          <el-option key="2" label="晚餐" value="2"></el-option>
          <el-option key="3" label="加餐" value="3"></el-option>
        </el-select>
        <el-input
          v-model="query.recipeName"
          placeholder="食谱名称"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary"  @click="handleSearch"
          ><el-icon style="margin-right: 5px"><Search /></el-icon
            >搜索</el-button
        >
        <el-button type="primary" @click="handleAdd">添加食谱</el-button>
        <el-popconfirm
          title="确定要删除选中食谱？"
          confirm-button-text="确定"
          cancel-button-text="取消"
          @confirm="deleteAll"
        >
          <template #reference>
            <el-button  type="danger">删除选中</el-button>
          </template>
        </el-popconfirm>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelect"
        v-loading="loading"
      >
        <el-table-column type="selection" width="70" align="center"/>
        <el-table-column label="序号" width="65" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="recipeName"
          label="食谱名称"
          min-width="20%"
          align="center"
        ></el-table-column>
        <el-table-column label="封面图片" min-width="20%" align="center">
          <template #default="scope">
            <el-image :src="scope.row.logoImg"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="stars" label="推荐指数" min-width="20%" align="center">
          <template #default="scope">
            <div class="demo-rate-block">
              <el-rate disabled v-model="scope.row.stars" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="就餐类别" min-width="20%" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.category == '0'
                  ? 'danger'
                  : scope.row.category == '1'
                  ? 'success'
                  : scope.row.category == '2'
                  ? 'success'
                  : scope.row.category == '3'
                  ? 'success'
                  : 'warning'
              "
            >
              {{
                scope.row.category == '0'
                  ? '早餐'
                  : scope.row.category == '1'
                  ? '午餐'
                  : scope.row.category == '2'
                  ? '晚餐'
                  : scope.row.category == '3'
                  ? '加餐'
                  : '其他'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型"  align="center" min-width="10%" >
          <template #default="scope">
            <el-tag
              :type="
                scope.row.type == '0' ? '' : scope.row.gender == '1' ? '' : ''
              "
            >
              {{
                scope.row.type == '0'
                  ? '普通'
                  : scope.row.type == '1'
                  ? '推荐'
                  : '其他'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalCaloric"
          label="总热量(千卡)"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalCarbohydrate"
          label="总碳水(g)"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalProtein"
          label="总蛋白质(g)"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalFat"
          label="总脂肪(g)"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="185" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              ><el-icon style="margin-right: 5px"><Edit /></el-icon
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除此食谱？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger"><el-icon style="margin-right: 5px"><Delete /></el-icon
                  >删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange(query.currentPage)"
        />
      </div>
    </div>

  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'

import qs from 'qs'
export default {
  setup() {
    const router = useRouter()

    const loading = ref(true)
    
    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }
    const cancelForm = (formEl) => {
      centerDialogVisible.value = false
      centerDialogAddVisible.value = false
      resetForm(formEl)
    }
    // 处理时间函数
    function dateTOString(date) {
      var source = new Date(date)
      var yy = source.getFullYear().toString()
      var mm = source.getMonth() + 1
      mm = mm < 10 ? '0' + mm.toString() : mm.toString()
      var dd = source.getDate()
      dd = dd < 10 ? '0' + dd.toString() : dd.toString()
      var aa = yy + '-' + mm + '-' + dd
      return aa
    }
    //更新表单
    const submitForm = async (formEl) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          request
            .request({
              url: '/user/updateUser',
              method: 'post',
              data: {
                userId: ruleForm.userId,
                username: ruleForm.username,
                gender: ruleForm.gender,
                height: ruleForm.height,
                weight: ruleForm.weight,
                phone: ruleForm.phone,
                bmi: ruleForm.bmi,
                type: ruleForm.type,
                status: ruleForm.status,
                specialCondition: ruleForm.specialCondition,
                birthDay: dateTOString(ruleForm.birthDay),
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '更新成功',
                  message: '成功更新用户信息',
                })

                getData()
                // centerDialogVisible.value = false
                // router.go(0)
              } else {
                ElNotification({
                  title: '更新失败',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              ElNotification({
                title: '更新失败',
                message: '请联系管理员检查失败原因',
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }
    const ruleForm = reactive({
      avator: '',
      category: 0,
      directions: '',
      logoImg: '',
      recipeId: '',
      stars: 0,
      totalCaloric: 0,
      totalCarbohydrate: 0,
      totalFat: 0,
      recipeName: '',
      totalProtein: 0,
      type: 0,
    })
    const rules = reactive({
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
      gender: [
        {
          required: true,
          message: '请选择性别',
          trigger: 'change',
        },
      ],
      height: [
        {
          required: true,
          message: '请输入身高',
          trigger: 'blur',
        },
      ],
      weight: [
        {
          required: true,
          message: '请输入体重',
          trigger: 'blur',
        },
      ],
      phone: [
        {
          required: true,
          message: '请输入电话号码',
          trigger: 'blur',
        },
      ],
      bmi: [
        {
          required: false,
          message: '请输入bmi值',
          trigger: 'blur',
        },
      ],
      specialCondition: [
        {
          required: true,
          message: '请选择特殊类型',
          trigger: 'change',
        },
      ],
    })
    const ruleFormRef = ref()
    // const centerDialogVisible = ref(false)
    // const centerDialogAddVisible = ref(false)
    const query = reactive({
      category: '',
      recipeName: '',
      currentPage: 1,
      pageSize: 5,
    })
    const tableData = ref([])
    const totalCount = ref(0)

    // 获取表格数据
    const getData = () => {
      request
        .request({
          url: '/recipe/getRecipesByPageAndCondition',
          params: {
            category: query.category,
            recipeName: query.recipeName,
            currentPage: query.currentPage,
            pageSize: query.pageSize,
          },
          method: 'get',
        })
        .then((res) => {
          //获取当前页的数据
          tableData.value = res.data.data.rows
          //获取总记录数
          totalCount.value = res.data.data.count
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
        })
    }
    getData()
    // 查询操作
    const handleSearch = () => {
      getData()
    }
    // 分页导航
    const handleCurrentChange = (val) => {
      loading.value = true
      query.currentPage = val
      getData()
    }

    //批量删除
    const selectArray = ref('')
    //选中
    const handleSelect = (val) => {
      selectArray.value = []
      for (const iterator of val) {
        selectArray.value.push(iterator.recipeId)
      }
    }
    //删除全部选中
    const deleteAll = () => {
      loading.value = true
      // JSON.stringify(selectArray.value)
      request
        .request({
          url: '/recipe/deleteRecipe',
          method: 'get',
          params: {
            recipeIds: selectArray.value,
          },
          paramsSerializer: (params) => {
            return qs.stringify(params, { indices: false })
          },
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()
            loading.value = false
            ElNotification({
              title: '删除成功',
              message: '成功删除选中食谱',
            })
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    // 删除操作
    const handleDelete = (index, row) => {
      loading.value = true
      request
        .request({
          url: '/recipe/deleteRecipe?recipeIds=' + row.recipeId,
          method: 'get',
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()
            ElNotification({
              title: '删除成功',
              message: '成功删除食谱信息',
            })
            loading.value = false
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    const handleEdit = (index, value) => {
      router.push({
        name: 'recipeEdit',
        query: {
          recipeId: value.recipeId,
        },
      })
    }
    //添加用户
    const handleAdd = () => {
      router.push('recipeAdd')
    }

    return {
      loading,
      resetForm,
      cancelForm,
      ruleFormRef,
      submitForm,
      ruleForm,
      rules,
      // centerDialogVisible,
      // centerDialogAddVisible,
      query,
      totalCount,
      tableData,
      getData,
      handleEdit,
      handleSearch,
      handleCurrentChange,
      handleDelete,
      handleAdd,
      handleSelect,
      selectArray,
      deleteAll,
      dateTOString,
    }
  },
}
</script>
<style lang="scss" scoped>
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  // padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .container {
  flex: 1;
  border-right: solid 1px var(--el-border-color);
}

.demo-date-picker .container .block {
  border-right: none;
}

.demo-date-picker .container .block:last-child {
  border-top: solid 1px var(--el-border-color);
}

.demo-date-picker .container:last-child {
  border-right: none;
}

.demo-date-picker {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
